package org.querycreator.converter;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import org.hibernate.criterion.Criterion;
import org.querycreator.core.QuerySpecification;
import org.querycreator.core.Restriction;


/**
 * 
 * @author Luciano Molinari
 *
 */
public class Converter implements Serializable {
	private static final long serialVersionUID = -187880329686545206L;
	
	public static List<Criterion> convertToListOfHibernateCriterion(QuerySpecification querySpecification) {
		List<Criterion> list = new ArrayList<Criterion>();
		for(Restriction restriction : querySpecification.getRestrictions()) {
			list.add(restriction.getOperator().createCriterion(restriction.getFieldName(), restriction.getFieldValue()));
		}
		return list;
	}
	
	public static ClauseAndParameters convertToClauseAndParameters(QuerySpecification querySpecification) {
		if(querySpecification.getRestrictions().size() == 0) {
			return new ClauseAndParameters("", new ArrayList<Object>());
		}
		List<Object> parameters = new ArrayList<Object>();
		StringBuilder clause = new StringBuilder("where ");
		int i = 1;
		for(Restriction restriction : querySpecification.getRestrictions()) {
			if(i > 1) {
				clause.append(" and ");
			}
			clause.append(restriction.getOperator().createSql(restriction.getFieldName()));
			parameters.add(restriction.getFieldValue());
			i++;
		}
		return new ClauseAndParameters(clause.toString(), parameters);
	}
	
}